using System;
using System.Data;
using System.Collections;
using APP.QUANLY.Common;
using RMAS.DAL;

namespace RMAS.DAL
{
    /// <summary>
    /// Summary description for DM_METERIAL.
     /// </summary>
	public class DM_METERIALDao
    {
	    private string _SQLSelectByKey;
	    private string _SQLUpdate;
	    private string _SQLInsert;
	    private string _SQLDelete;
	    private string _SQLSelectAll;

        #region Properties

        public IDbConnection _dbConnection;

        public IDbConnection DbConnection
        {
            get { return _dbConnection; }
            set { _dbConnection = value; }
        }

        #endregion
        
        #region Constructor

        public DM_METERIALDao()
        {
            _dbConnection = null;
		    InitSqlQuery();
        }

        public DM_METERIALDao(IDbConnection con)
        {
            _dbConnection = con;
            InitSqlQuery();
        }

        #endregion


        private void ToLowerQuery()
        {
            _SQLDelete = _SQLDelete.ToLower();
            _SQLUpdate = _SQLUpdate.ToLower();
            _SQLInsert = _SQLInsert.ToLower();
            _SQLSelectByKey = _SQLSelectByKey.ToLower();
        }

        private void ToUpperQuery()
        {
            _SQLDelete = _SQLDelete.ToUpper();
            _SQLUpdate = _SQLUpdate.ToUpper();
            _SQLInsert = _SQLInsert.ToUpper();
            _SQLSelectByKey = _SQLSelectByKey.ToUpper();
        }

        #region InitSqlQuery
        private void InitSqlQuery()
       {
            string query;

            query = @"SELECT ID, Name, Price, MinNumStore, MaxNumStore, UnitID, GroupID, IsUsed, FirstBalancer, IDPOS FROM DM_METERIAL WHERE (ID = @ID)";
	        _SQLSelectByKey = query;

            query = @"UPDATE DM_METERIAL SET Name = @Name, Price = @Price, MinNumStore = @MinNumStore, MaxNumStore = @MaxNumStore, UnitID = @UnitID, GroupID = @GroupID, IsUsed = @IsUsed, FirstBalancer = @FirstBalancer, IDPOS = @IDPOS WHERE (ID = @ID)";
	        _SQLUpdate = query;

            query = @"INSERT INTO DM_METERIAL VALUES (@ID, @Name, @Price, @MinNumStore, @MaxNumStore, @UnitID, @GroupID, @IsUsed, @FirstBalancer, @IDPOS)";
	        _SQLInsert = query;

            query = @"DELETE FROM DM_METERIAL WHERE (ID = @ID)";
	        _SQLDelete = query;

            query = @"SELECT ID, Name, Price, MinNumStore, MaxNumStore, UnitID, GroupID, IsUsed, FirstBalancer, IDPOS FROM DM_METERIAL";
	        _SQLSelectAll = query;
        }
        #endregion
        public void LoadByCommandText(string commandtext, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = commandtext;

				if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        #region Save & Delete
        private void Save(DM_METERIAL obj, IDbTransaction trans, bool isExisting)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                command = _dbConnection.CreateCommand();

                if (!isExisting) { command.CommandText = _SQLInsert + ";"; }
                else { command.CommandText = _SQLUpdate + ";"; }

                         DalTools.addDbDataParameter(command, "ID", obj.ID, DbType.String);
                         DalTools.addDbDataParameter(command, "Name", obj.Name, DbType.String);
         DalTools.addDbDataParameter(command, "Price", obj.Price, DbType.Double);
         DalTools.addDbDataParameter(command, "MinNumStore", obj.MinNumStore, DbType.Double);
         DalTools.addDbDataParameter(command, "MaxNumStore", obj.MaxNumStore, DbType.Double);
         DalTools.addDbDataParameter(command, "UnitID", obj.UnitID, DbType.String);
         DalTools.addDbDataParameter(command, "GroupID", obj.GroupID, DbType.String);
         DalTools.addDbDataParameter(command, "IsUsed", obj.IsUsed, DbType.String);
         DalTools.addDbDataParameter(command, "FirstBalancer", obj.FirstBalancer, DbType.Double);
         DalTools.addDbDataParameter(command, "IDPOS", obj.IDPOS, DbType.String);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Delete(DM_METERIAL obj, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                //throw new DalException("Connection has not been set.");
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = _SQLDelete + ";";

                         DalTools.addDbDataParameter(command, "ID", obj.ID, DbType.String);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Insert(DM_METERIAL obj, IDbTransaction trans)
        {
            Save(obj, trans, false);
        }
        public void Update(DM_METERIAL obj, IDbTransaction trans)
        {
            Save(obj, trans, true);
        }
        #endregion

        #region Command Execute & Read Properties
     
        private DM_METERIALList SelectListByCommand(IDbCommand command)
        {
            DM_METERIALList list = new DM_METERIALList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
		DM_METERIAL obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new DM_METERIAL();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }
		
        private DM_METERIALList SelectListByCommand(IDbCommand command, IDbTransaction trans)
        {
            DM_METERIALList list = new DM_METERIALList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				DM_METERIAL obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
				command.Transaction = trans;
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new DM_METERIAL();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private void DeleteListByCommand(IDbCommand command, IDbTransaction trans)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                if (trans != null) { command.Transaction = trans; }
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
	
        private void ReadProperties(DM_METERIAL obj, IDataReader reader)
        {
            try
            {
                                if(!(reader["ID"] is DBNull))
		{
			obj.ID = (string)reader["ID"];
		}
                if(!(reader["Name"] is DBNull))
		{
			obj.Name = (string)reader["Name"];
		}
                if(!(reader["Price"] is DBNull))
		{
			obj.Price = (double)reader["Price"];
		}
                if(!(reader["MinNumStore"] is DBNull))
		{
			obj.MinNumStore = (double)reader["MinNumStore"];
		}
                if(!(reader["MaxNumStore"] is DBNull))
		{
			obj.MaxNumStore = (double)reader["MaxNumStore"];
		}
                if(!(reader["UnitID"] is DBNull))
		{
			obj.UnitID = (string)reader["UnitID"];
		}
                if(!(reader["GroupID"] is DBNull))
		{
			obj.GroupID = (string)reader["GroupID"];
		}
                if(!(reader["IsUsed"] is DBNull))
		{
			obj.IsUsed = (string)reader["IsUsed"];
		}
                if(!(reader["FirstBalancer"] is DBNull))
		{
			obj.FirstBalancer = (double)reader["FirstBalancer"];
		}
                if(!(reader["IDPOS"] is DBNull))
		{
			obj.IDPOS = (string)reader["IDPOS"];
		}
            }
            catch (Exception ex)
            {
                throw new DalException("Failed to read properties from DataReader.", ex);
            }
        }
        #endregion
      
        public DM_METERIAL SelectByKey(string ID)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "ID", ID, DbType.String);
      	    DM_METERIALList list =  SelectListByCommand(command);

            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }

        public DM_METERIAL SelectByKey(string ID, IDbTransaction trans)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "ID", ID, DbType.String);
      	    DM_METERIALList list =  SelectListByCommand(command, trans);
			
            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }
		
        public DM_METERIALList SelectAll()
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            if (!StaticVar.IsServer)
            {
                _SQLSelectAll = _SQLSelectAll + " WHERE IDPOS = @IDPOS";
                DalTools.addDbDataParameter(command, "IDPOS", StaticVar.CPUID, DbType.String);
            }
            command.CommandText = _SQLSelectAll;
      	    DM_METERIALList list =  SelectListByCommand(command);
	        return list;
        }
	public DM_METERIALList SelectAll(IDbTransaction trans)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            if (!StaticVar.IsServer)
            {
                _SQLSelectAll = _SQLSelectAll + " WHERE IDPOS = @IDPOS";
                DalTools.addDbDataParameter(command, "IDPOS", StaticVar.CPUID, DbType.String);
            }
            command.CommandText = _SQLSelectAll;
      	    DM_METERIALList list =  SelectListByCommand(command, trans);
	        return list;
        }
         public DM_METERIALList SelectByCommand(string Command)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = Command;
      	    DM_METERIALList list =  SelectListByCommand(command);
	        return list;
        }

        public DM_METERIALList SelectByCondition(DM_METERIAL obj, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM DM_METERIAL " + GetCondtionQuery(obj) + ";";
            FillParamToCommand(command, obj);
            DM_METERIALList list = SelectListByCommand(command, trans);
            return list;
        }
		
		 public DM_METERIALList SelectByCondition(DM_METERIAL obj)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM DM_METERIAL " + GetCondtionQuery(obj) + ";";
            FillParamToCommand(command, obj);
            DM_METERIALList list = SelectListByCommand(command);
            return list;
        }
        private void DeleteByCondition(DM_METERIAL obj, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "DELETE FROM DM_METERIAL " + GetCondtionQuery(obj) + ";";
            FillParamToCommand(command, obj);
            DeleteListByCommand(command, trans);
        }

        #region Make Condition Query & Fill Param from Condition to Command
        private string GetCondtionQuery(DM_METERIAL obj)
        {
            if (obj == null) { return ""; }
            string s = "";
            	if (obj.IsSetID)
	{
    	    s += " AND ID = @ID ";
	}
	if (obj.IsSetName)
	{
    	    s += " AND Name = @Name ";
	}
	if (obj.IsSetPrice)
	{
    	    s += " AND Price = @Price ";
	}
	if (obj.IsSetMinNumStore)
	{
    	    s += " AND MinNumStore = @MinNumStore ";
	}
	if (obj.IsSetMaxNumStore)
	{
    	    s += " AND MaxNumStore = @MaxNumStore ";
	}
	if (obj.IsSetUnitID)
	{
    	    s += " AND UnitID = @UnitID ";
	}
	if (obj.IsSetGroupID)
	{
    	    s += " AND GroupID = @GroupID ";
	}
	if (obj.IsSetIsUsed)
	{
    	    s += " AND IsUsed = @IsUsed ";
	}
	if (obj.IsSetFirstBalancer)
	{
    	    s += " AND FirstBalancer = @FirstBalancer ";
	}
	if (obj.IsSetIDPOS)
	{
    	    s += " AND IDPOS = @IDPOS ";
	}
            if (s.Length > 0)
            {
                s =" WHERE "+s.Substring(4);
                return s;
            }
            return "";
        }

        private void FillParamToCommand(IDbCommand command, DM_METERIAL obj)
        {
	    if (obj == null) { return;}
            	            if (obj.IsSetID)
            {
            	DalTools.addDbDataParameter(command, "ID", obj.ID, DbType.String); 
            }
            if (obj.IsSetName)
            {
            	DalTools.addDbDataParameter(command, "Name", obj.Name, DbType.String); 
            }
            if (obj.IsSetPrice)
            {
            	DalTools.addDbDataParameter(command, "Price", obj.Price, DbType.Double); 
            }
            if (obj.IsSetMinNumStore)
            {
            	DalTools.addDbDataParameter(command, "MinNumStore", obj.MinNumStore, DbType.Double); 
            }
            if (obj.IsSetMaxNumStore)
            {
            	DalTools.addDbDataParameter(command, "MaxNumStore", obj.MaxNumStore, DbType.Double); 
            }
            if (obj.IsSetUnitID)
            {
            	DalTools.addDbDataParameter(command, "UnitID", obj.UnitID, DbType.String); 
            }
            if (obj.IsSetGroupID)
            {
            	DalTools.addDbDataParameter(command, "GroupID", obj.GroupID, DbType.String); 
            }
            if (obj.IsSetIsUsed)
            {
            	DalTools.addDbDataParameter(command, "IsUsed", obj.IsUsed, DbType.String); 
            }
            if (obj.IsSetFirstBalancer)
            {
            	DalTools.addDbDataParameter(command, "FirstBalancer", obj.FirstBalancer, DbType.Double); 
            }
            if (obj.IsSetIDPOS)
            {
            	DalTools.addDbDataParameter(command, "IDPOS", obj.IDPOS, DbType.String); 
            }
        }
        #endregion
    }
}